package com.qf.sl.youshare.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import com.qf.sl.youshare.*;
import com.qf.sl.youshare.adapters.StorePlatformAdapter;
import com.qf.sl.youshare.model.Category;
import com.qf.sl.youshare.model.Product;
import com.qf.sl.youshare.tasks.ProductListTask;
import com.qf.sl.youshare.tasks.TaskProcessor;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

/**
 * Created by IDEA
 * User : sl
 * on 2015/2/5.
 * 16:20
 */
public class StorePlatformFragment extends Fragment implements TaskProcessor, AdapterView.OnItemClickListener {

    /**
     * 设置分类部分一行显示几个,需要代码进行设置
     */
    public static final int NUN_COLUMN = 3;
    private boolean hasFirstLoad = false;

    private List<Product> products;
    private StorePlatformAdapter adapter;

    private HashMap<String,Integer> list = new HashMap<String, Integer>();

    /**
     * 子分类ID,如果这个id没有设置,那么就显示的是 平台商品列表,
     *  就需要包含分类九宫格,
     * 如果设置了,显示特定的分类下的商品列表
     *  不需要显示九宫格
     */
    private String categoryId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        products = new LinkedList<Product>();

        Bundle arguments = getArguments();

        if (arguments != null) {
            categoryId = arguments.getString(Constants.ARG_SUB_CATEGORY_ID);
        }
    }

    private void initMapList(){
        list.put("3",R.drawable.cate_cloth);
        list.put("4",R.drawable.cate_shoot);
        list.put("5",R.drawable.cate_huwai);
        list.put("6",R.drawable.cate_riyong);
        list.put("7",R.drawable.cate_electric);
        list.put("8",R.drawable.cate_huazhuang);
        list.put("9",R.drawable.cate_food);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View ret = inflater.inflate(R.layout.fragment_store_platform, container, false);

        GridView gridView = (GridView) ret.findViewById(R.id.store_platform_products);

        adapter = new StorePlatformAdapter(getActivity(), products);

        initMapList();

        gridView.setAdapter(adapter);

        gridView.setOnItemClickListener(this);

        //分类商品部分九宫格界面

        GridView categoryView = (GridView) ret.findViewById(R.id.store_platform_categories);
        //由于分类没有图片, 因此我们可以使用自己定义的图片进行设置, 既然
        //就可以采用SimpleAdapter

        if (categoryView != null) {

            //如果有分类ID,那么就隐藏
            if (categoryId != null) {
                categoryView.setVisibility(View.GONE);
            }

            categoryView.setOnItemClickListener(this);

            categoryView.setNumColumns(NUN_COLUMN);

            LinkedList<Map<String, Object>> data = new LinkedList<Map<String, Object>>();

            DataStorage dataStorage = DataStorage.getInstance();
            Category category = dataStorage.getCategory("2");//平台产品 ID 为 2

            if (category != null) {
                List<Category> subCategories = category.getSubCategories();

                //检查 GridView 一行显示几个,根据当前的数量进行一个运算,显示整行

                int numColumns = NUN_COLUMN;
                int size = subCategories.size();

                int row = size / numColumns;

                int realCount = 0;

                if (row > 0){
                    realCount = row * numColumns;
                }

                int count = 0;

                for (Category subCategory : subCategories) {

                    count++;

                    if (count > realCount){
                        break;
                    }

                    String name = subCategory.getName();

                    String id = subCategory.getId();

                    Integer integer = list.get(id);

                    HashMap<String,Object> map = new HashMap<String, Object>();

                    map.put("title",name);

                    map.put("icon",integer);

                    data.add(map);

                }
            }

            SimpleAdapter categoryAdapter = new SimpleAdapter(
                    getActivity(),
                    data,
                    R.layout.item_platform_category,
                    new String[]{"title", "icon"},
                    new int[]{R.id.item_category_title, R.id.item_category_icon}
            );

            categoryView.setAdapter(categoryAdapter);
        }

        if (!hasFirstLoad){
            ProductListTask task = new ProductListTask(this);

            String cid = "2";

            //如果需要显示特定分类下的商品,那么就使用categoryID,
            // 否则就是2 -> "平台商品"
            if (categoryId != null) {
                cid = categoryId;
            }

            task.execute(cid,"10");
        }

        return ret;
    }

    @Override
    public void processResult(JSONObject jsonObject) {
        //TODO 显示商品的列表

        if (jsonObject != null) {
//            System.out.println("jsonObject = " + jsonObject);

            try {
                int code = jsonObject.getInt("code");
                if (code == 1){
                    //TODO 正确数据,需要解析
                    JSONObject msg = jsonObject.getJSONObject("msg");
                    JSONObject data = msg.getJSONObject("data");
                    Iterator keys = data.keys();

                    List<Product> productList = new LinkedList<Product>();

                    while (keys.hasNext()){
                        Object key = keys.next();
                        JSONObject object = data.getJSONObject((String) key);

                        Product product = new Product();//高内聚
                        product.parseJSON(object);
                        productList.add(product);
                    }

                    //注意: 如果是刷新数据,那么products成员变量就要清空,然后
                    //          用productList里面的内容添加到 products 中,
                    //          相当于ListView重新加载
                    //     如果需要实现"加载更多"的操作,那么就不能够清空 list, 而是直接添加

                    products.addAll(productList);
                    adapter.notifyDataSetChanged();


                }else {
                    String msg = jsonObject.getString("msg");
                    System.out.println("msg = " + msg);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            hasFirstLoad = true;
        }
    }

    /**
     * 商品分类点击
     * @param parent AdapterView<?>
     * @param view View
     * @param position int
     * @param id long
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //TODO 商品分类点击

        int parentId = parent.getId();

        if (parentId == R.id.store_platform_categories){
            DataStorage dataStorage = DataStorage.getInstance();
            Category category = dataStorage.getCategory("2");
            if (category != null) {
                List<Category> subCategories = category.getSubCategories();

                //取子分类
                Category cat = subCategories.get(position);

                String catId = cat.getId();
                Intent intent = new Intent(getActivity(), SubCategoryActivity.class);
                intent.putExtra(Constants.INTENT_KEY_CATEGORY_ID,catId);
                startActivity(intent);

            }
        }else if (parentId == R.id.store_platform_products) {
            if (products != null) {
                Product product = products.get(position);

                Intent intent = new Intent(getActivity(), PlatformGoodsActivity.class);

                String goodsId = product.getGoodsId();

                intent.putExtra("goodsId", goodsId);

                startActivity(intent);

            }
        }

    }
}